<template>
    <img
        ref="img"
        :src="src"
        @click="popShown = true"
        v-bind="$attrs"
        class="img"
    />
    <a-modal v-model:value="popShown" :clickBgToClose="true">
        <img
            ref="popImg"
            :src="src"
            @click.left="popShown = false"
            @wheel="onWheel"
            style="
                max-width: 50%;
                max-height: 50%;
                transform: scale(1, 1);
                transition: transform 200ms;
            "
        />
    </a-modal>
</template>

<style lang="scss" scoped>
.img {
    object-fit: scale-down;
}
</style>

<script>
import AModal from './AModal.vue'

export default {
    name: 'AFitimg',
    components: { AModal },
    emits: ['info'],
    props: {
        src: {
            type: String,
            required: true,
        },
    },

    data() {
        return {
            popShown: false,
        }
    },
    mounted() {
        let imgEl = this.$refs.img
        imgEl.addEventListener('load', this.onLoad)
    },
    methods: {
        onLoad() {
            let imgEl = this.$refs.img
            let oWidth = imgEl.naturalWidth
            let oHeight = imgEl.naturalHeight

            this.$emit('info', {
                width: oWidth,
                height: oHeight,
            })
        },
        onWheel(e) {
            let popImg = this.$refs.popImg
            let toAddFactor = e.deltaY < 0 ? 0.1 : -0.1
            let transform = popImg.style.transform
            let scaleStr = transform.substring(transform.indexOf('(') + 1, transform.indexOf(','))
            let scale = Number.parseFloat(scaleStr)
            let newScale = scale + toAddFactor
            let newTransform = `scale(${newScale}, ${newScale})`
            popImg.style.transform = newTransform
        },
    },
}
</script>